package sim.dynamics;

import com.jme3.math.FastMath;
import com.jme3.math.Vector3f;
import java.util.Random;
import sim.models.BaseModel;

/**
 *
 * @author Ahmad
 */
public class RandomizedModelMotion implements IModelMotion {
    int gridWidth, gridHeight;
    float speed, d1, d2;
    Vector3f target, delta;
    public static Random rand = new Random();
    
    
    public RandomizedModelMotion(int gridWidth, int gridHeight, float speed) {
        this.gridWidth = gridWidth;
        this.gridHeight = gridHeight;
        this.speed = speed;
    }

    public void move(BaseModel model) {
        Vector3f pos = model.getLocalTranslation().setY(0);
        if (target == null) {
            target = new Vector3f();
            float minDistance = 0.5f * Math.min(gridWidth, gridHeight);
            do {
                float firstRand = rand.nextFloat();
                float secondRand = rand.nextFloat();
                target.set(
                        (firstRand - 0.5f) * gridWidth,
                        model.getLocalTranslation().getY(),
                        (secondRand - 0.5f) * gridHeight);
            } while (pos.distance(target) < minDistance);
            if (FastMath.abs(target.getX()) > gridWidth) target.setX(0);
            if (FastMath.abs(target.getZ()) > gridHeight) target.setZ(0);
            delta = target.subtract(pos).mult(speed / 1000.0f);
            model.lookAt(delta);
            d2 = pos.distance(target);
        } else {
            model.walk(delta);
            d1 = d2;
            d2 = pos.distance(target);
            if (d1 < d2)
                target = null;
        }
    }
}
